//
//  GroupCreateViewController.m
//  SportSocial
//
//  Created by yull on 15/1/29.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "GroupCreateViewController.h"
#import "UIPlaceHolderTextView.h"
#import "StarView.h"
#import "GroupNet.h"
#import "LocationManager.h"
#import "UIViewController+TextHUD.h"
#import <UIViewController+MBProgressHUD.h>
#import "UIImageView+WebCache.h"
#import "LocationManager.h"

@interface GroupCreateViewController () <UITextFieldDelegate,UITextViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate>

@property (nonatomic, strong) UIScrollView *inputScrollView;

@property (nonatomic, strong) UIImageView *topImageView;
@property (nonatomic, strong) UIImageView *headImageView;
@property (nonatomic, strong) UITextField *nameTextField;
@property (nonatomic, strong) UITextField *addressTextField;
@property (nonatomic, strong) UIPlaceHolderTextView *introTextView;

@property (nonatomic, strong) UIView *editingView;
@property (nonatomic, assign) CGFloat keyboarHeight;

@property (nonatomic, strong) UIImage *clubAvatar;

@end

@implementation GroupCreateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNavibar];
    
    CGRect rect = CGRectMake(0, 0, self.view.width, self.view.height);
    self.inputScrollView = [[UIScrollView alloc] initWithFrame:rect];
    [self.view addSubview:self.inputScrollView];
    
    [self initContentView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onKeyboardChage:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onKeyboardHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)initNavibar
{
    self.navigationItem.title = @"创建俱乐部";
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 44, 44);
    [rightButton setTitle:@"完成" forState:UIControlStateNormal];
    [rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [rightButton addTarget:self action:@selector(onCompleteButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarButton;
    
    [self addCommonBackButton];
}

- (void)initContentView
{
    CGRect rect = CGRectMake(0, 0, self.view.width, 130);
    self.topImageView = [[UIImageView alloc] initWithFrame:rect];
    self.topImageView.image = [UIImage imageNamed:@"user_info_bg"];
    self.topImageView.userInteractionEnabled = YES;
    [self.inputScrollView addSubview:self.topImageView];
    
    if (self.group) {
        rect = CGRectMake(0, 15, 60, 60);
        self.headImageView = [[UIImageView alloc] initWithFrame:rect];
        self.headImageView.centerX = self.view.width/2;
        [self.headImageView sd_setImageWithURL:[NSURL URLWithString:self.group.icon] placeholderImage:[UIImage imageNamed:@"julebu"]];
        [self.topImageView addSubview:self.headImageView];
        
        rect = CGRectMake(0, self.headImageView.bottom + 15, 80, 30);
        UIButton *photoButton = [UIButton buttonWithType:UIButtonTypeCustom];
        photoButton.frame = rect;
        photoButton.centerX = self.view.centerX;
        photoButton.backgroundColor = RGB(182, 89, 9);
        [photoButton setTitle:@"上传照片" forState:UIControlStateNormal];
        [photoButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        photoButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
        [photoButton addTarget:self action:@selector(selectClubAvatar:) forControlEvents:UIControlEventTouchUpInside];
        [self.topImageView addSubview:photoButton];
    }
    
    rect = CGRectMake(10, self.topImageView.bottom, self.view.width - 20, 45);
    self.nameTextField = [[UITextField alloc] initWithFrame:rect];
    self.nameTextField.contentVerticalAlignment = UIControlContentHorizontalAlignmentCenter;
    self.nameTextField.placeholder = @"请输入名称";
    self.nameTextField.textColor = [UIColor blackColor];
    self.nameTextField.font = [UIFont systemFontOfSize:16.0f];
    self.nameTextField.delegate = self;
    if (self.group) {
        self.nameTextField.text = self.group.name;
    }
    [self.inputScrollView addSubview:self.nameTextField];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(10, self.nameTextField.bottom - 0.5f, self.nameTextField.width, 0.5f)];
    lineView.backgroundColor = RGB(237, 237, 237);
    [self.inputScrollView addSubview:lineView];
    
    UIImageView *locationImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_ad"]];
    locationImageView.size = locationImageView.image.size;
    locationImageView.left = 30;
    locationImageView.top = self.nameTextField.bottom + 13;
    [self.inputScrollView addSubview:locationImageView];
    
    rect.origin.x = locationImageView.right + 10;
    rect.origin.y = self.nameTextField.bottom;
    rect.size.width = self.view.width - rect.origin.x - 10;
    rect.size.height = 40;
    self.addressTextField = [[UITextField alloc] initWithFrame:rect];
    self.addressTextField.contentHorizontalAlignment = UIControlContentVerticalAlignmentCenter;
    self.addressTextField.placeholder = @"请输入地址";
    self.addressTextField.textColor = [UIColor blackColor];
    self.addressTextField.font = [UIFont systemFontOfSize:14.0f];
    self.addressTextField.delegate = self;
    if (self.group) {
        self.addressTextField.text = self.group.address;
    } else if ([LocationManager shareInstance].address.length) {
        self.addressTextField.text = [LocationManager shareInstance].address;
    }
    [self.inputScrollView addSubview:self.addressTextField];
    
    lineView = [[UIView alloc] initWithFrame:CGRectMake(10, self.addressTextField.bottom - 0.5f, self.view.width - 20, 0.5f)];
    lineView.backgroundColor = RGB(237, 237, 237);
    [self.inputScrollView addSubview:lineView];
    
    lineView = [[UIView alloc] initWithFrame:CGRectMake(10, self.addressTextField.bottom - 0.5f, self.view.width - 20, 0.5f)];
    lineView.backgroundColor = RGB(237, 237, 237);
    [self.inputScrollView addSubview:lineView];
    
    rect = CGRectMake(15, lineView.bottom + 15, self.view.width - 30, 160);
    UIView *introBackView = [[UIView alloc] initWithFrame:rect];
    introBackView.backgroundColor = RGB(229, 244, 241);
    [self.inputScrollView addSubview:introBackView];
    
    rect = CGRectMake(5, 5, introBackView.width - 10, 20);
    UILabel *label = [[UILabel alloc] initWithFrame:rect];
    label.backgroundColor = [UIColor clearColor];
    label.text = @"介绍";
    label.font = [UIFont systemFontOfSize:14.0f];
    label.textColor = RGB(61, 106, 94);
    [introBackView addSubview:label];

    rect = CGRectMake(25, label.bottom, introBackView.width - 50, introBackView.height - label.bottom - 10);
    self.introTextView = [[UIPlaceHolderTextView alloc] initWithFrame:rect];
    self.introTextView.delegate = self;
    self.introTextView.placeholder = @"请输入俱乐部简介";
    self.introTextView.placeholderColor = RGB(148, 177, 69);
    self.introTextView.backgroundColor = [UIColor clearColor];
    self.introTextView.textColor = RGB(148, 177, 69);;
    self.introTextView.font = [UIFont systemFontOfSize:13.0f];
    if (self.group) {
        self.introTextView.text = self.group.annou;
    }
    [introBackView addSubview:self.introTextView];
    
    self.inputScrollView.contentSize = CGSizeMake(self.view.width, MAX(self.view.height, introBackView.bottom + 20));
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    self.editingView = textField;
    
    if (self.keyboarHeight > 0) {
        [self updateFrame];
    }
    return YES;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    self.editingView = textView.superview;
    return YES;
}

- (void)onKeyboardChage:(NSNotification *)notification
{
    self.keyboarHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
    [self updateFrame];
}

- (void)onKeyboardHide:(NSNotification *)notification
{
    self.keyboarHeight = 0;
    
    [self updateFrame];
}

- (void)updateFrame
{
    if (self.keyboarHeight == 0) {
        self.inputScrollView.contentInset = UIEdgeInsetsZero;
        self.editingView = nil;
    }else {
        CGFloat visibleHeight = self.view.height - self.keyboarHeight - 30;
        
        CGFloat bottom = self.editingView.bottom;
        
        CGFloat delta = bottom - visibleHeight;
        if (delta > 0) {
            self.inputScrollView.contentInset = UIEdgeInsetsMake(0, 0, delta, 0);
            [self.inputScrollView setContentOffset:CGPointMake(0, bottom -  visibleHeight) animated:YES];
        }
    }
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Private
- (void)selectClubAvatar:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册",@"拍照", nil];
    actionSheet.tag = 101;
    [actionSheet showInView:self.view];
}

- (void)onCompleteButtonClick:(id)sender
{
    [self.view endEditing:YES];
    
    self.inputScrollView.contentInset = UIEdgeInsetsZero;
    self.inputScrollView.contentOffset = CGPointZero;
    
    NSString *name = self.nameTextField.text;
    NSString *address = self.addressTextField.text;
    NSString *annou = self.introTextView.text;
    CLLocation *location = [LocationManager shareInstance].location;
    CGFloat longitude = 0.0f;
    CGFloat latitude = 0.0f;
    if (location) {
        longitude = location.coordinate.longitude;
        latitude = location.coordinate.latitude;
    }
    
    NSString *errorMsg = @"";
    if (name.length == 0) {
        errorMsg = @"请填写群名称";
    }
    
    if (address.length == 0) {
        errorMsg = @"请填写地址";
    }
    
    if (errorMsg.length > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:errorMsg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }else if (!self.group) {
        [self showHUD];
        [GroupNet createGroupWithName:name address:address longitude:longitude latitude:latitude annou:annou successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
            [self hideHUD];
            BOOL success = [[responseObject objectForKey:@"success"] boolValue];
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self hideHUD];
                    [self showText:@"创建群成功，请等待管理员审核!"];
                    
                    [self.navigationController performSelector:@selector(popViewControllerAnimated:) withObject:nil afterDelay:1];
                });
            } else {
                NSString *message = [responseObject objectForKey:@"message"];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showText:message time:2];
                });
            }
        } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self hideHUD];
                [self showText:@"网络连接失败" time:2];
            });
        }];
    } else {
        [self showHUD];
        [GroupNet updateGroupWithGroupId:self.group.group_id name:name annou:annou successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
            [self hideHUD];
            BOOL success = [[responseObject objectForKey:@"success"] boolValue];
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showText:@"修改群信息成功!"];
                });
            } else {
                NSString *message = [responseObject objectForKey:@"message"];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showText:message time:2];
                });
            }
        } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self hideHUD];
                [self showText:@"网络连接失败" time:2];
            });
        }];
    }
}

- (void)updateGroupIconWithGroupId:(UInt64)groupId
{
    [self showHUD];
    [GroupNet uploadGroupIcon:self.clubAvatar groupId:groupId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self hideHUD];
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self hideHUD];
                [self showText:@"上传群头像成功!"];
            });
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideHUD];
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self pickPhoto];
    }else if (buttonIndex == 1) {
        [self takePhoto];
    }
}

#pragma mark - 图片
- (void)takePhoto
{
    BOOL rearCameraAvailable = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];//前
    BOOL frontCameraAvailable = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
    
    if (!rearCameraAvailable && !frontCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"此设备相机不可用" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    NSUInteger sourceType = 0;//初始化调用相机相册的方法
    sourceType = UIImagePickerControllerSourceTypeCamera;//调用相册
    
    UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)pickPhoto
{
    NSUInteger sourceType = 0;//初始化调用相机相册的方法
    sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;//调用相机
    
    UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [self.navigationController presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //要上传的图片
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    self.clubAvatar = image;
    
    self.headImageView.image = image;
    
    if (!self.group || !self.group.group_id) {
        return;
    }
    
    [self updateGroupIconWithGroupId:self.group.group_id];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

@end
